package net.qhzw.vip.qiyu.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.alicloud.sms.ISmsService;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import lombok.extern.slf4j.Slf4j;
import net.qhzw.vip.qiyu.handler.MyException;
import net.qhzw.vip.qiyu.model.GuaranteeSiteUser;
import net.qhzw.vip.qiyu.model.SendSmsParam;
import net.qhzw.vip.qiyu.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Autowired
    private ISmsService smsService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /***
     * 发送短信
     * @param sendSmsParam
     * @return
     */
    @Override
    public boolean sendTo(SendSmsParam sendSmsParam) {
        log.info("发送短信{}", JSON.toJSONString(sendSmsParam, true));
        SendSmsRequest request = redisVerify(sendSmsParam);
        try {
            SendSmsResponse sendSmsResponse = smsService.sendSmsRequest(request);
            String code = sendSmsResponse.getCode();
            if ("OK".equals(code)) {
                return true;
            }
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }

    /***
     * 发送短信
     * @param sendSmsParam
     */
    @Override
    public boolean send(SendSmsParam sendSmsParam) {
        log.info("发送短信{}", JSON.toJSONString(sendSmsParam, true));
        try {
            SendSmsResponse sendSmsResponse = smsService.sendSmsRequest(new SendSmsRequest());
            String code = sendSmsResponse.getCode();
            if ("OK".equals(code)) {
                return true;
            }
        }catch (Exception e){
            log.error("发送短信失败: {}", JSON.toJSONString(e, true));
        }
        return false;

    }

    /***
     * 发送短信提醒取消担保
     */
    @Override
    public void sendRemind(SendSmsParam sendSmsParam, GuaranteeSiteUser guaranteeSiteUser) {
        log.info("发送短信提醒取消担保{}", JSON.toJSONString(guaranteeSiteUser, true));
        log.info("发送短信提醒取消担保{}", JSON.toJSONString(sendSmsParam, true));
        SendSmsRequest request = buildSmsRequest2(sendSmsParam, guaranteeSiteUser);
        try {
            SendSmsResponse sendSmsResponse = smsService.sendSmsRequest(request);
            String code = sendSmsResponse.getCode();
        } catch (ClientException e) {
            log.error("[发送短信提醒取消担保错误： ]{}", JSON.toJSONString(e, true));
        }
    }

    private SendSmsRequest buildSmsRequest2(SendSmsParam sendSmsParam, GuaranteeSiteUser guaranteeSiteUser) {
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(sendSmsParam.getMobile()); //发送给谁
        sendSmsRequest.setSignName("青海骑遇网络科技有限公司");
        sendSmsRequest.setTemplateCode("SMS_235819772"); // 模板的Code--动态改变
        Map<String, String> map = new HashMap<>();
        map.put("company", guaranteeSiteUser.getGuaranteeCompany());
        map.put("guaranteeSite", guaranteeSiteUser.getGuaranteeSite());
        map.put("realname", guaranteeSiteUser.getRealName());
        String param = JSON.toJSONString(map);
        System.out.println(JSON.toJSONString(map));
        //sendSmsRequest.setTemplateParam("{\"company\":\"" + 222211 + "\"}");
        sendSmsRequest.setTemplateParam(param);
        return sendSmsRequest;
    }


    /***
     * redis
     * @return
     */
    private SendSmsRequest redisVerify(SendSmsParam sms) {
        String code = stringRedisTemplate.opsForValue().get("SMS:FORGOT_VERIFY:" + sms.getMobile());
        String numbers = RandomUtil.randomNumbers(6);
        log.info("发送短信验证码: {}", numbers);
        sms.setCode(numbers);
        if (code == null) {
            stringRedisTemplate.opsForValue().set("SMS:FORGOT_VERIFY:" + sms.getMobile(), numbers, 5, TimeUnit.MINUTES);
            stringRedisTemplate.opsForValue().set("SMS:FORGOT_VERIFY:COUNT:" + sms.getMobile(), String.valueOf(1), 5, TimeUnit.MINUTES);
            return buildSmsRequest(sms);
        }
        String countStr = stringRedisTemplate.opsForValue().get("SMS:FORGOT_VERIFY:COUNT:" + sms.getMobile());
        Integer count = Integer.valueOf(countStr);
        if (count <= 3) {
            stringRedisTemplate.opsForValue().set("SMS:FORGOT_VERIFY:" + sms.getMobile(), numbers, 5, TimeUnit.MINUTES);
            stringRedisTemplate.opsForValue().set("SMS:FORGOT_VERIFY:COUNT:" + sms.getMobile(), String.valueOf(++count), 5, TimeUnit.MINUTES);
            return buildSmsRequest(sms);
        } else {
            throw new MyException(500, "验证码校验过频繁，请稍后再试");
        }
    }


    /***
     * 构建发送短信的请求对象
     * @param sms
     * @return
     */
    private SendSmsRequest buildSmsRequest(SendSmsParam sms) {
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(sms.getMobile()); //发送给谁
        sendSmsRequest.setSignName("青海骑遇网络科技有限公司");
        sendSmsRequest.setTemplateCode(sms.getTemplateCode()); // 模板的Code--动态改变
        String code = sms.getCode();
        stringRedisTemplate.opsForValue().set("SMS:FORGOT_VERIFY:" + sms.getMobile(), code, 5, TimeUnit.MINUTES);
        sendSmsRequest.setTemplateParam("{\"code\":\"" + sms.getCode() + "\"}");
        return sendSmsRequest;
    }


}
